﻿/***************************************************************************
	Copyright (C) 2010 RapidWebDev Organization (Author: Eunge, Legal Name: Jian Liu, Email: eunge.liu@gmail.com)

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ***************************************************************************/

using System;
using System.Drawing;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using WebGridView = System.Web.UI.WebControls.GridView;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using BaoJianSoft.Common;
using BaoJianSoft.Web.Extensions.Controls;

namespace BaoJianSoft.Web.Extensions.DynamicPages
{
	/// <summary>
	/// Class to render gridview inside buttons, view, edit and delete.
	/// </summary>
	public class ButtonsTemplate : ITemplate
	{
		private GridViewConfiguration configuration;

		/// <summary>
		/// Event fires on clicking view button.
		/// </summary>
		public event EventHandler<GridViewPrimaryKeyFieldEventArgs> Viewing;

		/// <summary>
		/// Event fires on clicking edit button.
		/// </summary>
		public event EventHandler<GridViewPrimaryKeyFieldEventArgs> Editing;

		/// <summary>
		/// Event fires on clicking delete button.
		/// </summary>
		public event EventHandler<GridViewPrimaryKeyFieldEventArgs> Deleting;

		/// <summary>
		/// Event fires to authoritize button visibility inside of gridview while binding.
		/// </summary>
		public event EventHandler<GridViewButtonBindingEventArgs> Authoritizing;

		/// <summary>
		/// Construct buttons template.
		/// </summary>
		/// <param name="configuration"></param>
		public ButtonsTemplate(GridViewConfiguration configuration)
		{
			this.configuration = configuration;
		}

		/// <summary>
		/// When implemented by a class, defines the System.Web.UI.Control object that child controls and templates belong to. 
		/// These child controls are in turn defined within an inline template.
		/// </summary>
		/// <param name="container"></param>
		public void InstantiateIn(Control container)
		{
			(container as DataControlFieldCell).Attributes["AllowCellClickable"] = "false";

			if (this.configuration.ViewButton != null)
			{
				ViewIconButton viewIconButton = new ViewIconButton()
				{
					ID = "ViewIconButton",
					Configuration = this.configuration.ViewButton
				};

                viewIconButton.CssClass += " ViewIconButton";
				viewIconButton.Command += new CommandEventHandler(this.OnCommand);
				viewIconButton.DataBinding += new EventHandler(this.OnDataBinding);
				container.Controls.Add(viewIconButton);
				container.Controls.Add(new HtmlGenericControl("span") { InnerText = " " });
				WebUtility.RegisterAsyncPostBackControl(viewIconButton);
			}

			if (this.configuration.EditButton != null)
			{
				EditIconButton editIconButton = new EditIconButton()
				{
					ID = "EditIconButton",
					Configuration = this.configuration.EditButton
				};

                editIconButton.CssClass += " EditIconButton";
				editIconButton.Command += new CommandEventHandler(this.OnCommand);
				editIconButton.DataBinding += new EventHandler(this.OnDataBinding);
				container.Controls.Add(editIconButton);
				container.Controls.Add(new HtmlGenericControl("span") { InnerText = " " });
				WebUtility.RegisterAsyncPostBackControl(editIconButton);
			}

			if (this.configuration.DeleteButton != null)
			{
				DeleteIconButton deleteIconButton = new DeleteIconButton()
				{
					ID = "DeleteIconButton",
					Configuration = this.configuration.DeleteButton
				};

                deleteIconButton.CssClass += " DeleteIconButton";
				deleteIconButton.Command += new CommandEventHandler(this.OnCommand);
				deleteIconButton.DataBinding += new EventHandler(this.OnDataBinding);
				container.Controls.Add(deleteIconButton);
				WebUtility.RegisterAsyncPostBackControl(deleteIconButton);
			}
		}

		private void OnCommand(object sender, CommandEventArgs e)
		{
			System.Web.UI.WebControls.LinkButton linkbutton = sender as System.Web.UI.WebControls.LinkButton;
			switch (linkbutton.CommandName.ToLowerInvariant())
			{
				case "view":
					if (this.Viewing != null) this.Viewing(this, new GridViewPrimaryKeyFieldEventArgs(linkbutton.CommandArgument.ToString()));
					break;
				case "edit":
					if (this.Editing != null) this.Editing(this, new GridViewPrimaryKeyFieldEventArgs(linkbutton.CommandArgument.ToString()));
					break;
				case "delete":
					if (this.Deleting != null) this.Deleting(this, new GridViewPrimaryKeyFieldEventArgs(linkbutton.CommandArgument.ToString()));
					break;
			}
		}

		private void OnDataBinding(object sender, EventArgs e)
		{
			try
			{
				System.Web.UI.WebControls.LinkButton linkbutton = sender as System.Web.UI.WebControls.LinkButton;
				object dataItem = ((GridViewRow)linkbutton.NamingContainer).DataItem;
				object fieldValue = DataBinder.Eval(dataItem, this.configuration.PrimaryKeyFieldName);
				linkbutton.CommandArgument = fieldValue == null ? null : fieldValue.ToString();
				linkbutton.Visible = !string.IsNullOrEmpty(linkbutton.CommandArgument); // CommandArgument is Primary Key value.

				if (linkbutton.Visible)
				{
					GridViewRowButtonTypes buttonType = (GridViewRowButtonTypes)Enum.Parse(typeof(ButtonTypes), linkbutton.CommandName);
					GridViewButtonBindingEventArgs arg = new GridViewButtonBindingEventArgs(buttonType, dataItem);
					if (this.Authoritizing != null)
					{
						this.Authoritizing(this, arg);
						linkbutton.Visible = arg.Visible;
					}
				}
			}
			catch(Exception exp)
			{
				Logger.Instance(this).Warn(exp);
			}
		}
	}
}

